--
-- Author: shunguo.chen
-- Date: 2019-05-02 15:23:35
--
-- JewelTransformPanel 宝石转换界面
--

--local TabsBtn = require("app.widget.TabsBtn")
local IconRender = require("app.widget.renders.IconRender")
local ResRender = require("app.widget.renders.ResRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local JewelTargetRender = import(".renders.JewelTargetRender")

local ClassRef = app.mvc.createPanelClass(...)

function ClassRef.create(node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init()
    return sprite
end


function ClassRef:init(data)
    self.super.init(self, data)

    -- timeling动画
    self._timeline = self:getTimeline()
    self:playAction(false)

    local panel = self._ui.Panel

    -- left 宝石列表
    local leftPanel = panel:getChildByName("Panel_left")
    local typePanel = leftPanel:getChildByName("Panel_top")
--[[
    self._typeRedPoint1 = typePanel:getChildByName("dot_1")
    self._typeRedPoint2 = typePanel:getChildByName("dot_2")
    local btns = {
        typePanel:getChildByName("Button_1"),
        typePanel:getChildByName("Button_2"),
    }
    for i,btn in ipairs(btns) do
        btn:setTag(i)
    end
    local function onTabsBtn(index)
        if self._curIdx then
            self._curIdx = index
            self:switchJewelType()
        else
            self._curIdx = index
        end
    end
    local function onSelectBtn(btn, b)
        local tag = btn:getTag()
        local nameText = typePanel:getChildByName("name_" .. tag)
        if nameText then
            nameText:setOpacity(b and 255 or 125)
        end
    end
    self.tabsBtn = TabsBtn.new(btns, onTabsBtn, 1, nil, onSelectBtn)
    --]]

    self:switchJewelType(2)
    local params = {
        renderClass = IconRender,
        perNum = 4,
        gapY = 6,
        isMultipleLayer = true,
        cellEventProxy = function(eventName, render)
            self:_setCurCellModel(render:getCellModel())
            self:_onSelectSource(render:getData())
        end,
    }
    self._jewelSV = ListViewVertical.new(leftPanel:getChildByName("ScrollView") , params)

    self._tickBtn = leftPanel:getChildByName("Button_tick")
    self._tickBtn:addClickEventListener(function()
        local isBright = self._tickBtn:isBright()
        self._tickBtn:setBright(not isBright)
        executeFunc(self._onOperate, "transform_withEquip", isBright)
    end)

    -- right
    self._resRender = ResRender.create(self._ui.Panel_money)
    self._resRender:setData({type=Enums.TipsType.daibi, id=92, num=0})
    self._goldRender = ResRender.create(self._ui.Panel_gold)
    self._goldRender:setData({type=Enums.TipsType.daibi, id=99, num=0})

    -- 转换展示
    local rightPanel = panel:getChildByName("Panel_right")
    self._sourceRender = IconRender.create(rightPanel:getChildByName("icon_1"))
    self._sourceRender:setClickEnable(false)
    self._sourcePanel = rightPanel:getChildByName("data_1")

    self._targetRender = IconRender.create(rightPanel:getChildByName("icon_2"))
    self._targetRender:setClickEnable(false)
    self._targetPanel = rightPanel:getChildByName("data_2")

    self._switchBtn = rightPanel:getChildByName("Button")
    self._switchBtn:addClickEventListener(function()
        if self._sourceRender:getData() then
            executeFunc(self._onOperate, "transform_openTarget", self._sourceRender:getData())
        end
    end)

    -- 消耗道具
    local costRenders = {}
    local costRenderPosXs = {}
    local node, render
    for i=1,3 do
        node = rightPanel:findChild("Panel_stuff/icon_" .. i)
        render = IconRender.create(node)
        render:setTipEnable(true)
        costRenders[i] = render
        costRenderPosXs[i] = render:getPositionX()
    end
    self._costRenders = costRenders
    self._costRenderPosXs = costRenderPosXs

    self._okBtn = rightPanel:getChildByName("Button_enter")
    self._okBtn:addClickEventListener(function()
        if self._sourceRender:getData() == nil then
            display.pushToast(L("chooseRecastJewel"))
        elseif self._targetRender:getData() == nil then
            display.pushToast(L("chooseObtainJewel"))
        elseif not self._isItemEnough then
            display.pushToast(L("recastCostNotEnough"))
        else
            executeFunc(self._onOperate, "transform_confirm", 
                self._sourceRender:getData(), self._targetRender:getData())
        end
    end)

    -- 切换目标面板
    local targetListNode = panel:findChild("list")
    display.nodeRemoveForNotHit(targetListNode:getChildByName("Panel"), function()
        self._targetListNode:setVisible(false)
    end)
    local targetRenders = {}
    for i=1,20 do
        node = targetListNode:findChild("Panel/node_" .. i)
        if node then
            render = JewelTargetRender.create(node)
            render:onBtnClick(function(sender)
                self:_onSelectTarget(sender:getData())
            end)
            targetRenders[i] = render
        else
            break
        end
    end
    self._targetListNode = targetListNode
    self._targetRenders = targetRenders
end

function ClassRef:playAction(b)
    if b then
        self._timeline:gotoFrameAndPlay(0, true)
    else
        self._timeline:gotoFrameAndPause(0)
    end
end

-- tp 宝石类型
-- 1（蓝色宝石）
-- 2（紫色宝石）
function ClassRef:switchJewelType(tp)
    self._curIdx = tp
    executeFunc(self._onOperate, "transform_jewelType", self._curIdx)
end

function ClassRef:setWithEquip(b)
    self._tickBtn:setBright(not b)
end

function ClassRef:refreshResNum()
    self._resRender:refreshNum()
    self._goldRender:refreshNum()
end

function ClassRef:_setCurCellModel(cellModel)
    if self._curCellModel then
        if self._curCellModel.cell then
            self._curCellModel.cell:setSelected(false)
        else
            self._curCellModel:setUIState("selected", false)
        end
    end

    if cellModel.cell then
        cellModel.cell:setSelected(true)
    else
        cellModel:setUIState("selected", true)
    end

    self._curCellModel = cellModel
end

-- jewels   宝石列表
-- jewelUid 选中宝石uid
function ClassRef:refresh(jewels, jewelUid)
    self._targetListNode:setVisible(false)

    if jewels == nil or #jewels == 0 then
        self._ui.Panel_tips:setVisible(true)
        self._jewelSV:setVisible(false)
        self:_onSelectSource(nil)
    else
        self._ui.Panel_tips:setVisible(false)
        self._jewelSV:setVisible(true)

        self._jewelSV:reloadData(jewels)

        local selectIdx = 1
        if jewelUid then
            for i,jewel in ipairs(jewels) do
                if jewel.uid == jewelUid then
                    selectIdx = i
                    break
                end
            end
        end

        local cellModel = self._jewelSV:getCellModelByIndex(selectIdx)
        self:_setCurCellModel(cellModel)
        self:_onSelectSource(jewels[selectIdx])
    end
end

function ClassRef:updateCostItems()
    local jewel = self._sourceRender:getData()
    self:_refreshCostItems(jewel)
end

function ClassRef:_refreshJewelDetail(node, jewel)
    local name = jewel and jewel:getName(true) or ""
    local desc = jewel and jewel:getDesc() or ""
    local iconList = jewel and jewel:getPosShowIconList() or {}

    node:getChildByName("name"):setString(name)
    node:getChildByName("data"):setString(desc)

    -- 只有4个，取中间4个icon即可
    local iconNode, icon
    for i=2,5 do
        iconNode = node:getChildByName("icon" .. i)
        if iconNode then
            icon = iconList[i-1]
            iconNode:setVisible(icon ~= nil)
            if icon then
                iconNode:loadTexture(icon)
            end
        end
    end
end

function ClassRef:_refreshCostItems(jewel)
    -- 填充消耗，并根据个数排位置（最多三个）
    self._isItemEnough = true
    local costItems = jewel and jewel:getTransformCostItems() or {}
    local len = #costItems
    local item, hasNum
    for i,render in ipairs(self._costRenders) do
        item = costItems[i]
        render:setVisible(item ~= nil)
        if item then
            hasNum = UD:getNumByRenderData(item)
            render:setData(item)
            render:setHasAmount(hasNum, true)
            self._isItemEnough = self._isItemEnough and hasNum >= item:getAmount()

            if len == 1 then
                render:setPositionX(self._costRenderPosXs[2])
            elseif len == 2 then
                render:setPositionX((self._costRenderPosXs[i] + self._costRenderPosXs[i+1])/2)
            else
                render:setPositionX(self._costRenderPosXs[i])
            end
        end
    end
end

-- 选择来源jewel，刷新界面
function ClassRef:_onSelectSource(jewel)
    self._sourceRender:setData(jewel)
    self:_refreshJewelDetail(self._sourcePanel, jewel)
    self:_onSelectTarget(nil)

    self:_refreshCostItems(jewel)

    executeFunc(self._onOperate, "transform_selectJewel", jewel)
end

-- 选择目标jewel
function ClassRef:_onSelectTarget(jewel)
    self._targetListNode:setVisible(false)

    self._targetRender:setData(jewel)
    self:_refreshJewelDetail(self._targetPanel, jewel)
end

-- 目标list
function ClassRef:showTargetList(jewels)
    self._targetListNode:setVisible(true)
    for i,render in ipairs(self._targetRenders) do
        render:setData(jewels[i])
    end
end

return ClassRef